package cn.fx.baseweb.handler;

import cn.fx.framework.utils.CookieUtil;
import cn.fx.framework.utils.StringUtils;
import cn.fx.framework.web.AbstractApplicationHandler;
import org.springframework.context.ApplicationContext;

/**
 * 用来初始化应用程序：
 * activeString - 设置当前是什么状态（dev、test、debug、pre、prod）；
 * redisKeyPrefix - redis缓存的默认前缀；
 * 初始化CookieUtil：设置DOMAIN与PATH，cookieDomain - Cookie的域，cookiePath - Cookie的路径
 * 初始化缓存等
 */
public class BaseWebApplicationHandler extends AbstractApplicationHandler {

    private String activeString;
    private String redisKeyPrefix;
    private String cookieDomain;
    private String cookiePath;

    public BaseWebApplicationHandler(ApplicationContext applicationContext) {
        super(applicationContext);
        activeString = applicationContext.getEnvironment().getProperty("spring.profiles.active");
        redisKeyPrefix = applicationContext.getEnvironment().getProperty("site.redis.default-cache-prefix-keys-with");
        cookieDomain = applicationContext.getEnvironment().getProperty("site.session.cookie-domain");
        cookiePath = applicationContext.getEnvironment().getProperty("site.session.cookie-path");

        initCookieSetup();
    }

    //@Override
    public String getRedisKeyPrefix() {
        return redisKeyPrefix;
    }

    /**
     * 获取当前应用运行的环境：dev/test/debug/pre/prod
     * @return
     */
    @Override
    public String getCurEnvironment(){
        return activeString;
    }

    @Override
    public boolean isDevEnvironment() {
        return StringUtils.isNotEmpty(activeString) && activeString.equalsIgnoreCase("dev");
    }

    @Override
    public boolean isTestEnvironment() {
        return StringUtils.isNotEmpty(activeString) && activeString.equalsIgnoreCase("test");
    }

    @Override
    public boolean isDebugEnvironment() {
        return StringUtils.isNotEmpty(activeString) && activeString.equalsIgnoreCase("debug");
    }

    @Override
    public boolean isPreEnvironment() {
        return StringUtils.isNotEmpty(activeString) && activeString.equalsIgnoreCase("pre");
    }

    @Override
    public boolean isProdEnvironment() {
        return StringUtils.isNotEmpty(activeString) && activeString.equalsIgnoreCase("prod");
    }

    /**
     * 初始化CookieUtil：设置DOMAIN与PATH
     */
    void initCookieSetup() {
        if(!StringUtils.isNullOrEmpty(cookieDomain)) {
            CookieUtil.COOKIE_PATH = cookiePath;
        }
        if(!StringUtils.isNullOrEmpty(cookieDomain)){
            CookieUtil.COOKIE_DOMAIN = cookieDomain;
        }

    }
}
